package com.example.test;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.test.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private ActivityMainBinding binding;

    private static final int STORAGE_PERMISSION_REQUEST_CODE = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        // 检查并请求存储权限
        initPermissions();
    }

    private void initPermissions() {
        // 定义需要的权限数组
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };

        // 检查是否所有权限都已授予
        List<String> permissionsNotGranted = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsNotGranted.add(permission);
            }
        }

        // 如果有权限未授予，则请求权限
        if (!permissionsNotGranted.isEmpty()) {
            ActivityCompat.requestPermissions(
                    this,
                    permissionsNotGranted.toArray(new String[0]),
                    STORAGE_PERMISSION_REQUEST_CODE
            );
        } else {
            // 已经有权限
            startNext();
        }
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            String[] permissions,
            int[] grantResults
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            // 检查是否所有权限都被授予
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                // 所有权限都被授予
                startNext();
            } else {
                // 权限被拒绝
                binding.textView.setText("权限被拒绝");
                Toast.makeText(this, "权限被拒绝，部分功能可能无法使用", Toast.LENGTH_LONG).show();

                boolean shouldShowRequestPermissionRationale = false;
                for (String permission : permissions) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                        shouldShowRequestPermissionRationale = true;
                        break;
                    }
                }

                if (!shouldShowRequestPermissionRationale) {
                    // 权限被永久拒绝
                    showPermissionDeniedDialog();
                } else {
                    binding.textView.setText("存储权限被拒绝");
                    Toast.makeText(this, "存储权限被拒绝，部分功能可能无法使用", Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    }

    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限被拒绝")
                .setMessage("应用需要对应权限才能正常工作。请在设置中手动授予权限。")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                    binding.textView.setText("权限被拒绝");
                    Toast.makeText(this, "权限被拒绝，部分功能可能无法使用!!!", Toast.LENGTH_LONG).show();
                })
                .show();
    }

    private void startNext() {
        startActivity(new Intent(this, TestActivity.class));
    }
}